package com.yupi.soulba.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yupi.soulba.common.ErrorCode;
import com.yupi.soulba.exception.BusinessException;
import com.yupi.soulba.model.domain.User;
import com.yupi.soulba.model.domain.UserTeam;
import com.yupi.soulba.service.UserService;
import com.yupi.soulba.mapper.UserMapper;
import com.yupi.soulba.service.UserTeamService;
import com.yupi.soulba.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yupi.soulba.contant.UserConstant.ADMIN_ROLE;
import static com.yupi.soulba.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;
    
    @Resource
    private UserTeamService userTeamService;
    
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param username      用户昵称
     * @param profile       个性签名
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode    星球编号
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String username , String profile, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (username.length() > 36) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户昵称过长");
        }
        if (profile.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "个性签名过长");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 10) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUsername(username);
        user.setProfile(profile);
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }
    
    /**
     * 用户登录
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "此账号不存在");
        }
        queryWrapper.eq("userPassword", encryptPassword);
        user = userMapper.selectOne(queryWrapper);
        if(user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        if(originUser.getProfile() == null) {
            originUser.setProfile("");
        }
        if(originUser.getUsername() == null) {
            originUser.setUsername("");
        }
        if(originUser.getEmail() == null) {
            originUser.setEmail("");
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setProfile(originUser.getProfile());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 退出登录
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 根据标签搜索用户列表
     * @param tagNameList 用户要拥有的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList){
        //1. 先查绚所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //2. 在内存中判断是否包含要求的标签
        return userList.stream().filter((user) -> {
            String tagsStr = user.getTags();
            if(StringUtils.isBlank(tagsStr)){
                return false;
            }
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>(){}.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }
    
    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        long userId = user.getId();
        if(userId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如果是管理员，可以修改任何用户信息
        //如果是普通用户，只允许更新他自己的信息
        //如果登录用户和要修改信息的用户不一致，不允许修改
        if (!isAdmin(loginUser) && user.getId() != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if(oldUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

    /**
     * 根据用户id更新标签
     *
     * @param updateTags
     * @param userId
     * @return
     */
    @Override
    public int updateTagByUserId(String updateTags, long userId) {
        if(userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User oldUser = userMapper.selectById(userId);
        if(oldUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        oldUser.setTags(updateTags);
        return userMapper.updateById(oldUser);
    }

    /**
     * 根据队伍Id查看成员列表
     * @param viewTeamId
     * @return
     */
    @Override
    public List<User> viewTeamMembers(Long viewTeamId) {
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teamId", viewTeamId);
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        List<User> membersList = new ArrayList<>();
        for (UserTeam userTeam : userTeamList) {
            // 获得用户并脱敏
            User safetyUser = this.getSafetyUser(this.getById(userTeam.getUserId()));
            membersList.add(safetyUser);
        }
        return membersList;
    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if(request == null){
            return null;
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) userObj;
    }

    /**
     * 是否为管理员（传入前端请求判断）
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }
    
    /**
     * 是否为管理员（传入当前登录用户判断）
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 匹配最推荐用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        // 查询出所有用户（过滤掉标签为空的用户/过滤掉不需要的数据）
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 过滤掉不需要的数据 提升查询性能
        queryWrapper.select("id", "tags");
        // 过滤掉标签为空的用户 提升查询性能
        queryWrapper.isNotNull("tags");
        List<User> filterUserList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        List<Pair<User, Long>> userScoreList = new ArrayList<>();
        // 依次计算用户的相似度 并放入 userScoreList
        for (int i = 0; i < filterUserList.size(); i++) {
            User user = filterUserList.get(i);
            String userTags = user.getTags();
            // 无标签或者是当前用户自己不需要判断
            if(StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long score = AlgorithmUtils.minDistanceForTwoTagList(tagList, userTagList);
            // 循环放入 userScoreList
            userScoreList.add(new Pair<>(user, score));
        }
// 获取分数最高对应的下标列表
// List<Integer> maxDistanceIndexList = indexDistanceMap.keySet().stream()
// .limit(num).collect(Collectors.toList());
        // 自定义排序 根据Value（对应编辑距离）升序 取前num个最匹配用户
        List<Pair<User, Long>> topUserPairList = userScoreList.stream()
                .sorted((a, b) -> (int)(a.getValue() - b.getValue()))
                .limit(num).collect(Collectors.toList());
        // 获取排行前几的用户id列表 相似度递减排序 记录正确排序的列表
        List<Long> trueUserIdList = topUserPairList.stream()
                .map(pair -> pair.getKey().getId())
                .collect(Collectors.toList());
        // 前面查询为了性能 过滤掉不需要的字段 需要重新查回来才能返回给前端
        QueryWrapper<User> topUserIdQueryWrapper = new QueryWrapper<>();
        // 根据id列表查询对应top用户
        topUserIdQueryWrapper.in("id", trueUserIdList);
        // topUserIdQueryWrapper.in 导致查询结果混乱 
        // Map和userIdList把顺序重新排好
        //     user1        ,       user2        ,       user3
        // 1 => userList1   ;   2 => userList2   ;   3 => userList3
        // userList.index(0) 即为 user
        Map<Long, List<User>> topUserListUserMap = this.list(topUserIdQueryWrapper)
                .stream()
                // 用户脱敏
                .map(user -> getSafetyUser(user))
                // 根据用户id分组
                .collect(Collectors.groupingBy(User::getId));
        List<User> topUserList = new ArrayList<>();
        // 遍历正确排序的列表 从map中依次取值 得到完整且脱敏的最匹配用户列表
        for (Long userId : trueUserIdList) {
            topUserList.add(topUserListUserMap.get(userId).get(0));
        }
        return topUserList;
    }

    /**
     * 根据标签搜索用户 SQL查询版
     * @param tagNameList 用户要拥有的标签
     * @return
     */
    @Deprecated
    private List<User> searchUsersByTagsBySQL(List<String> tagNameList){
        if(CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
       QueryWrapper<User> queryWrapper = new QueryWrapper<>();
       // 拼接 and 查询
       // like '%Java%' and like '%Python%'
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags",tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }
}

